<template>
  <div class="department-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>部门列表</h3>
          <div class="header-actions">
            <el-button
              type="success"
              style="background-color: #67c23a; color: #ffffff; border-color: #67c23a"
              @click="handleAdd"
            >
              + 新增部门
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="departmentTree"
        border
        v-loading="loading"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        style="width: 100%"
      >
        <el-table-column prop="title" label="部门名称" min-width="200">
          <template #default="scope">
            <span
              :class="
                getDepartmentType(scope.row) === 2 ? 'external-department' : 'internal-department'
              "
            >
              {{ scope.row.title }}
              <span v-if="getDepartmentType(scope.row) === 2" class="external-tag">[外联]</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="部门类型" width="100">
          <template #default="scope">
            <el-tag :type="getDepartmentType(scope.row) === 2 ? 'info' : 'success'" size="small">
              {{ getDepartmentType(scope.row) === 2 ? '外联' : '内部' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="leader" label="负责人" width="150" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              style="background-color: #409eff; color: #ffffff; border-color: #409eff"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button
              size="small"
              type="success"
              style="background-color: #67c23a; color: #ffffff; border-color: #67c23a"
              @click="handleAddChild(scope.row)"
            >
              新增下级
            </el-button>
            <el-button
              size="small"
              style="background-color: #e6a23a; color: #ffffff; border-color: #e6a23a"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              style="background-color: #f56c6c; color: #ffffff; border-color: #f56c6c"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.id === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 部门详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      direction="rtl"
      size="50%"
      :before-close="handleDrawerClose"
      :class="getDrawerClass()"
    >
      <template #header>
        <div class="drawer-header">
          <el-icon class="drawer-icon" :class="getHeaderIconClass()">
            <Plus v-if="!isViewMode && !drawerTitle.includes('编辑')" />
            <Edit v-else-if="!isViewMode && drawerTitle.includes('编辑')" />
            <View v-else />
          </el-icon>
          <span>{{ drawerTitle }}</span>
        </div>
      </template>
      <div class="drawer-content">
        <el-form
          :model="detailForm"
          :rules="isViewMode ? {} : detailRules"
          ref="detailFormRef"
          label-width="100px"
          class="drawer-form"
        >
          <el-form-item label="上级部门" prop="pid">
            <el-tree-select
              v-model="detailForm.pid"
              :data="departmentTreeForSelect"
              node-key="id"
              :props="{ label: 'title', children: 'children' }"
              check-strictly
              placeholder="请选择上级部门"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
          <el-form-item label="部门名称" prop="title">
            <el-input
              v-model="detailForm.title"
              placeholder="请输入部门名称"
              :readonly="isViewMode"
            />
          </el-form-item>
          <el-form-item label="负责人">
            <el-select
              v-model="detailForm.leader_ids"
              multiple
              placeholder="请选择负责人"
              style="width: 100%"
              :disabled="isViewMode"
            >
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.name"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="detailForm.sort" :min="0" :disabled="isViewMode" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="detailForm.remark"
              type="textarea"
              placeholder="请输入备注"
              :rows="3"
              :readonly="isViewMode"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="handleDrawerClose">{{ isViewMode ? '关闭' : '取消' }}</el-button>
          <el-button
            v-if="!isViewMode"
            type="primary"
            :class="getFooterButtonClass()"
            @click="handleSave"
          >
            {{ isViewMode ? '关闭' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import { useUserStore } from '@/store'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Edit, Plus, View } from '@element-plus/icons-vue'
  import type { FormInstance } from 'element-plus'

  interface Department {
    id: number
    pid: number
    title: string
    leader: string
    leader_ids: number[] | string
    sort: number
    remark: string
    type: number // 1=内部，2=外联
    children?: Department[]
    user_count?: number
    [key: string]: any
  }

  interface User {
    id: number
    name: string
    [key: string]: any
  }

  const userStore = useUserStore()

  // 详情表单
  const detailForm = reactive({
    id: 0,
    pid: 0,
    title: '',
    leader_ids: [] as number[],
    sort: 0,
    remark: '',
    isExternal: false, // 是否为外联部门
  })

  // 表单验证规则
  const detailRules = {
    pid: [{ required: true, message: '请选择上级部门', trigger: 'change' }],
    title: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  }

  // 数据相关
  const departmentList = ref<Department[]>([])
  const userList = ref<User[]>([])
  const loading = ref(false)

  // 抽屉相关
  const drawerVisible = ref(false)
  const drawerTitle = ref('新增部门')
  const isViewMode = ref(false)

  // 表单引用
  const detailFormRef = ref<FormInstance>()

  // 处理抽屉关闭 - 删除重复定义

  // 计算属性 - 部门树形结构
  const departmentTree = computed(() => {
    // API返回的数据已经是树形结构，直接返回
    return departmentList.value
  })

  // 计算属性 - 部门树形结构（用于选择）
  const departmentTreeForSelect = computed(() => {
    // 排除当前编辑的部门及其子部门
    if (detailForm.id > 0) {
      const filteredDepartments = filterDepartments(departmentList.value, detailForm.id)
      return filteredDepartments
    }
    return departmentList.value
  })

  // 过滤部门（排除当前编辑的部门及其子部门）
  const filterDepartments = (departments: Department[], excludeId: number): Department[] => {
    return departments
      .filter(dept => dept.id !== excludeId)
      .map(dept => {
        const newDept = { ...dept }
        if (newDept.children && newDept.children.length > 0) {
          newDept.children = filterDepartments(newDept.children, excludeId)
        }
        return newDept
      })
      .filter(dept => {
        // 确保不是被排除部门的子部门
        return !isChildOrSelf(dept, excludeId)
      })
  }

  // 判断是否为子部门或自身
  const isChildOrSelf = (dept: Department, id: number): boolean => {
    if (dept.id === id) return true
    if (dept.pid === 0) return false
    const parent = departmentList.value.find(d => d.id === dept.pid)
    return parent ? isChildOrSelf(parent, id) : false
  }

  // 获取部门类型（内部或外联）
  const getDepartmentType = (dept: Department): number => {
    // 根据API返回的type字段判断，1=内部，2=外联
    return dept.type || 1
  }

  // 加载部门列表
  const loadDepartmentList = async () => {
    loading.value = true
    try {
      const res = await userStore.getDepartmentListAction()
      console.log('部门API响应:', res)
      if (res.code === 0) {
        departmentList.value = res.data as any[]
        console.log('部门数据已加载:', departmentList.value.length, '条记录')
        console.log('第一条部门数据:', departmentList.value[0])
      } else {
        ElMessage.error(res.msg || '获取部门列表失败')
        console.error('获取部门列表失败:', res)
      }
    } catch (error) {
      console.error('获取部门列表异常:', error)
      ElMessage.error('获取部门列表失败')
    } finally {
      loading.value = false
    }
  }

  // 加载用户列表 - 获取所有启用状态的用户
  const loadUserList = async () => {
    try {
      // 设置limit为较大值以获取所有用户，确保负责人下拉列表显示完整
      await userStore.getUserListAction({ status: 1, limit: 1000 })
      // 从store中获取用户列表数据
      userList.value = userStore.users
      console.log('用户列表已加载:', userList.value.length, '名员工')
    } catch (error) {
      ElMessage.error('获取用户列表失败')
      console.error('加载用户列表错误:', error)
    }
  }

  // 新增部门 - 修改：打开新增抽屉时重新加载用户列表，确保数据最新
  const handleAdd = async () => {
    drawerTitle.value = '新增部门'
    isViewMode.value = false
    Object.assign(detailForm, {
      id: 0,
      pid: 0,
      title: '',
      leader_ids: [],
      sort: 0,
      remark: '',
      isExternal: false,
    })

    // 打开抽屉前重新加载用户列表，确保下拉选项完整且最新
    await loadUserList()
    drawerVisible.value = true
  }

  // 新增下级部门 - 修改：打开新增下级部门抽屉时重新加载用户列表
  const handleAddChild = async (row: any) => {
    drawerTitle.value = '新增下级部门'
    isViewMode.value = false
    Object.assign(detailForm, {
      id: 0,
      pid: row.id,
      title: '',
      leader_ids: [],
      sort: 0,
      remark: '',
    })

    // 打开抽屉前重新加载用户列表，确保下拉选项完整且最新
    await loadUserList()
    drawerVisible.value = true
  }

  // 编辑部门 - 修改：打开编辑抽屉时重新加载用户列表，确保数据最新且完整
  const handleEdit = async (row: any) => {
    drawerTitle.value = '编辑部门'
    isViewMode.value = false
    Object.assign(detailForm, row)
    // 处理leader_ids为数组
    if (typeof row.leader_ids === 'string' && row.leader_ids) {
      detailForm.leader_ids = row.leader_ids.split(',').map(Number)
    } else {
      detailForm.leader_ids = []
    }

    // 打开抽屉前重新加载用户列表，确保下拉选项完整且最新
    await loadUserList()
    drawerVisible.value = true
  }

  // 获取抽屉样式类名
  const getDrawerClass = () => {
    if (isViewMode.value) {
      return 'view-drawer'
    }
    if (drawerTitle.value.includes('编辑')) {
      return 'edit-drawer'
    }
    return 'add-drawer'
  }

  // 获取底部按钮样式类名
  const getFooterButtonClass = () => {
    if (isViewMode.value) {
      return 'view-btn'
    }
    if (drawerTitle.value.includes('编辑')) {
      return 'edit-btn'
    }
    return 'add-btn'
  }

  // 获取header图标样式类名
  const getHeaderIconClass = () => {
    if (isViewMode.value) {
      return 'view-icon'
    }
    if (drawerTitle.value.includes('编辑')) {
      return 'edit-icon'
    }
    return 'add-icon'
  }

  // 查看部门详情 - 修改：打开查看抽屉时也重新加载用户列表，确保数据最新
  const handleView = async (row: any) => {
    drawerTitle.value = '查看部门'
    isViewMode.value = true
    Object.assign(detailForm, row)
    // 处理leader_ids为数组
    if (typeof row.leader_ids === 'string' && row.leader_ids) {
      detailForm.leader_ids = row.leader_ids.split(',').map(Number)
    } else {
      detailForm.leader_ids = []
    }

    // 打开抽屉前重新加载用户列表，确保显示数据最新
    await loadUserList()
    drawerVisible.value = true
  }

  // 关闭抽屉前的处理
  const handleDrawerClose = () => {
    drawerVisible.value = false
    // 重置表单
    if (detailFormRef.value) {
      detailFormRef.value.resetFields()
    }
  }

  // 保存部门
  const handleSave = () => {
    if (!detailFormRef.value) return

    detailFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          // 处理leader_ids为字符串
          const formData = { ...detailForm }
          if (Array.isArray(formData.leader_ids)) {
            formData.leader_ids = formData.leader_ids.join(',') as any
          }

          const res: any = await userStore.saveDepartmentAction(formData)
          if (res.code === 0) {
            ElMessage.success(res.msg || '保存成功')
            handleDrawerClose()
            loadDepartmentList()
          } else {
            ElMessage.error(res.msg || '保存失败')
          }
        } catch (error) {
          ElMessage.error('保存失败')
        }
      }
    })
  }

  // 删除部门
  const handleDelete = (row: any) => {
    ElMessageBox.confirm('确定要删除该部门吗？删除后不可恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res: any = await userStore.deleteDepartmentAction(row.id)
          if (res.code === 0) {
            ElMessage.success(res.msg || '删除成功')
            loadDepartmentList()
          } else {
            ElMessage.error(res.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 初始化加载
  onMounted(() => {
    loadDepartmentList()
    loadUserList()
  })
</script>

<style scoped>
  .department-container {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }

  .drawer-content {
    padding: 20px;
  }

  .drawer-form {
    max-width: 100%;
  }

  .drawer-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 15px 20px;
    border-top: 1px solid #eee;
  }

  /* 新增部门抽屉样式 */
  :deep(.add-drawer .el-drawer__header) {
    background: linear-gradient(90deg, #67c23a 0%, #85ce61 100%);
    color: #ffffff;
    margin-bottom: 0;
    padding: 15px 20px;
  }

  :deep(.add-drawer .el-drawer__header .el-drawer__close-btn) {
    color: #ffffff;
  }

  .add-btn {
    background-color: #67c23a;
    color: #ffffff;
    border-color: #67c23a;
  }

  /* 编辑部门抽屉样式 */
  :deep(.edit-drawer .el-drawer__header) {
    background: linear-gradient(90deg, #e6a23a 0%, #f3a847 100%);
    color: #ffffff;
    margin-bottom: 0;
    padding: 15px 20px;
  }

  :deep(.edit-drawer .el-drawer__header .el-drawer__close-btn) {
    color: #ffffff;
  }

  .edit-btn {
    background-color: #e6a23a;
    color: #ffffff;
    border-color: #e6a23a;
  }

  /* 查看部门抽屉样式 */
  :deep(.view-drawer .el-drawer__header) {
    background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
    color: #ffffff;
    margin-bottom: 0;
    padding: 15px 20px;
  }

  :deep(.view-drawer .el-drawer__header .el-drawer__close-btn) {
    color: #ffffff;
  }

  .view-btn {
    background-color: #409eff;
    color: #ffffff;
    border-color: #409eff;
  }

  /* 抽屉header样式 */
  :deep(.el-drawer__header) {
    margin-bottom: 0;
    padding: 15px 20px;
  }

  .drawer-header {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
  }

  .drawer-icon {
    margin-right: 8px;
    font-size: 16px;
    color: #ffffff;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    padding: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
  }

  .add-icon {
    background-color: rgba(255, 255, 255, 0.2);
  }

  .edit-icon {
    background-color: rgba(255, 255, 255, 0.2);
  }

  .view-icon {
    background-color: rgba(255, 255, 255, 0.2);
  }
</style>
